package love.contact;

import java.io.File;
import java.util.HashMap;

import love.contact.data.Setting;
import wwk.common.http.HttpEngine;
import wwk.common.http.HttpResponseData;
import wwk.common.http.HttpResponseInterface;
import wwk.common.json.JSONObject;
import wwk.common.util.FileUtil;
import wwk.common.util.JsonUtil;
import wwk.common.util.SysUtil;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.RemoteViews;

public class UpdateController implements HttpResponseInterface
{
	private enum UpdateStatus
	{
		UpdateIdle,
		UpdateChecking,
		UpdateDownloading,
	};

	private UpdateStatus updateStatus=UpdateStatus.UpdateIdle;
	private Context context;//used while donwloading
	private HttpEngine httpEngine;
	private Notification notification;
	private int downloadedSize;
	private int contentLength;
	private String downloadFilePath;

	static final private String server="www.wweike.cn";
	static final private String GetConfigUrlFormat="http://%s/contact/getConfig.php";
	static final private String GetApkUrlFormat="http://%s/contact/getApk.php";

	private Handler donwloadHandler=new Handler() 
	{
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			
			switch(msg.what)
			{
				case 0:
					{
						//downloading
						if(context!=null)
						{
							notification.contentView.setProgressBar(R.id.pb,contentLength,downloadedSize,false);
							NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
					        notificationManager.notify(1, notification);
					        
					        Log.d("percent",""+downloadedSize+":"+contentLength);
							
					        //finish
							if(httpEngine==null)
							{
								CharSequence title=null;
								
								if(contentLength>0 && downloadedSize>=contentLength)
								{
									title = context.getString(R.string.downloadFinish);
  
									//Toast.makeText(context, "download finish", Toast.LENGTH_SHORT).show();
									///notificationManager.cancel(1);
							    		
									updateStatus=UpdateStatus.UpdateIdle;
									
									install(context);
								}
								else
								{
									FileUtil.delete(downloadFilePath);
									title = context.getString(R.string.downloadFail);
									updateStatus=UpdateStatus.UpdateIdle;
								}
								
								notification.contentView.setTextViewText(R.id.down_tv,title);
					    			notificationManager.notify(1, notification);
								
								context=null;
							}
						}
					}
					break;
			}
		}
	};
	
	public void install(Context context)
	{
		String filePathName=getDownloadFilePath();
		SysUtil.openFile(filePathName, context);
	}
	
	private void addHeaders(HttpEngine httpEngine,Activity activity)
	{
		DisplayMetrics dm=SysUtil.getDisplayMetrics(activity);
		int versionCode=SysUtil.getVersionCode(activity);

		httpEngine.addRequestHead("widthPixels",""+dm.widthPixels);
		httpEngine.addRequestHead("heightPixels",""+dm.heightPixels);
		httpEngine.addRequestHead("SDK_INT",""+Build.VERSION.SDK_INT);
		httpEngine.addRequestHead("PRODUCT",""+Build.PRODUCT);
		httpEngine.addRequestHead("MODEL",""+Build.MODEL);
		httpEngine.addRequestHead("MANUFACTURER",""+Build.MANUFACTURER);
		httpEngine.addRequestHead("versionCode",""+versionCode);
		httpEngine.addRequestHead("channel",activity.getString(R.string.app_channel));
	}
	
	public void requestConfig(Activity activity)
	{
		this.context=activity;
		
		String url=String.format(GetConfigUrlFormat,server);
		//Log.d("request",url);
		
		httpEngine=new HttpEngine(this);
		httpEngine.setUrl(url);
		httpEngine.setResponsedInProgress(false);
		httpEngine.setBufferSize(1024*4);
		
		addHeaders(httpEngine,activity);
		
		httpEngine.request();
		
		updateStatus=UpdateStatus.UpdateChecking;
	}
	
	public boolean isDownloading()
	{
		return updateStatus==UpdateStatus.UpdateDownloading;
	}

	public void downloadNewVersion(Activity activity)
	{
		if(httpEngine!=null)
		{
			return;
		}
		
		this.context=activity;
		
		showDownloadingNotification(context);
		
		String url=String.format(GetApkUrlFormat,server);
		//Log.d("request",url);
		
		httpEngine=new HttpEngine(this);
		httpEngine.setUrl(url);
		httpEngine.setResponsedInProgress(true);
		httpEngine.setBufferSize(1024*4);
		
		addHeaders(httpEngine,activity);
		
		httpEngine.request();
		
		downloadedSize=0;
		contentLength=0;
		updateStatus=UpdateStatus.UpdateDownloading;
		
		setDownloadFilePath(context);
        	FileUtil.delete(downloadFilePath);
	}
	
	private void setDownloadFilePath(Context context)
	{
		String sdCard=FileUtil.getSdCardDir();
        if(sdCard!=null)
        {
        		downloadFilePath=sdCard+File.separator+SysUtil.getPackageName(context)+File.separator;
        		downloadFilePath=downloadFilePath+"contact.apk";
        }
	}
	
		private void showDownloadingNotification(Context context)
		{
	        int icon = R.drawable.icon;
	        CharSequence title = context.getString(R.string.downloading);
	        long when = System.currentTimeMillis();
	        
	        Intent notificationIntent = new Intent(context, MainTabActivity.class);
	        notificationIntent.putExtra("action","install");
	        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
	        notification = new Notification();
	        notification.icon=icon;
	        notification.when=when;
	        notification.contentIntent=contentIntent;
	        notification.contentView = new RemoteViews(context.getPackageName(),R.layout.common_download_notification); 
	        notification.contentView.setTextViewText(R.id.down_tv,title);
	        notification.contentView.setProgressBar(R.id.pb,0,0, false);
	        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
	        notificationManager.notify(1, notification);
		}

		public void onHttpResponsed(HttpResponseData httpResponseData) 
		{
			if(httpResponseData.responseFinished)
			{
				httpEngine=null;
			}
			
			if(updateStatus==UpdateStatus.UpdateChecking)
			{
				String jsonString=httpResponseData.getString();
				if(jsonString!=null)
				{
					JSONObject jsonObject=JsonUtil.createJsonObject(jsonString);
					boolean success=JsonUtil.getInt(jsonObject,"success", 0)==1;
					if(success)
					{
						JSONObject dataJsonObject=JsonUtil.getJsonObject(jsonObject, "data");
						int packageVCode=SysUtil.getVersionCode(context);
						int serverVCode=JsonUtil.getInt(dataJsonObject, "versionCode", packageVCode);
						String serverVName=JsonUtil.getString(dataJsonObject, "versionName");
						
						Setting setting=new Setting();
						setting.load(context);
						setting.serverVersionCode=serverVCode;
						setting.serverVersionName=serverVName;
						setting.requestTimestamp=System.currentTimeMillis();
						setting.save(context);
					}
				}
				
				context=null;
			}
			else if(updateStatus==UpdateStatus.UpdateDownloading)
			{
				downloadedSize+=httpResponseData.getBytesSize();
				if(httpResponseData.contentLength>0)
				{
					contentLength=httpResponseData.contentLength;
				}
				
		        if(downloadFilePath!=null)
		        {
			        	FileUtil.write(downloadFilePath, httpResponseData.bytes, httpResponseData.getBytesSize(), true);
		        }

				donwloadHandler.sendEmptyMessage(0);
			}
		}
		
		private String getDownloadFilePath() 
		{
			return downloadFilePath;
		}
}
